<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--      筛选-->
      <!--      分栏24占满 -->
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="标题" prop="title">
            <el-input
              v-model="queryParams.title"
              placeholder="请输入标题"
              clearable
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="编号" prop="problemId">
            <el-input
              v-model="queryParams.problemId"
              placeholder="请输入编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="作者" prop="authorId">
            <el-select
              style="width: 240px"
              v-model="queryParams.authorId"
              filterable
              remote
              reserve-keyword
              placeholder="请输入用户昵称"
              :remote-method="remoteGetUserList"
              :loading="userLoading">
              <el-option
                v-for="item in userList"
                :key="item.userId"
                :label="item.nickName"
                :value="item.userId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="选择状态"
              clearable
            >
              <el-option
                v-for="dict in sys_normal_disable"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="类型" prop="auth">
            <el-select
              v-model="queryParams.auth"
              placeholder="类型"
              clearable
            >
              <el-option
                v-for="dict in authList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="标签" prop="tagIds">
            <el-select
              v-model="queryParams.tagIds"
              multiple
              filterable
              remote
              clearable
              reserve-keyword
              placeholder="输入标签名称"
              :remote-method="remoteGetTagList"
              :loading="tagLoading">
              <el-option
                v-for="item in tagList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="题库" prop="problemTypeId">
            <el-select
              style="width: 100%"
              v-model="queryParams.problemTypeId"
              filterable
              clearable
              remote
              reserve-keyword
              placeholder="输入题库名称"
              :remote-method="remoteGetProblemType"
              :loading="problemTypeLoading">
              <el-option
                v-for="item in problemTypeList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="难度" prop="difficultyId">
            <el-select
              v-model="queryParams.difficultyId"
              filterable
              clearable
              remote
              reserve-keyword
              placeholder="输入难度名称"
              :remote-method="remoteGetDifficulty"
              :loading="problemDifficultyLoading">
              <el-option
                v-for="item in difficultyList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="multiple"
              @click="handleCorrection"
            >批改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              :disabled="multiple"
              @click="copyProblem"
            >复制</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-upload
              action=""
              :before-upload="beforeUpload"
              :httpRequest="defaultImport">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
              >导入</el-button>
            </el-upload>
          </el-col>
          <el-col :span="1.5">
            <el-upload
              action=""
              :httpRequest="fpsImport">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
              >fps导入</el-button>
            </el-upload>
          </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table row-key="id"
                  :highlight-current-row="type == 1"
                  ref="mainTable"
                  v-loading="loading"
                  :data="data"
                  @current-change="handleCurrentChange"
                  @selection-change="handleSelectionChange" >
          <el-table-column :reserve-selection="true"
                           :type="type == 1 ?'index' : 'selection'"
                           width="50"
                           align="center" />
          <el-table-column v-for="(item,index) in columns"
                           v-if="item.visible"
                           :key="index"
                           :label="item.label"
                           :prop="item.prop"
                           :width="item.width"
                            align="center">
            <template slot-scope="scope">
              <span  v-if="item.prop =='createTime'"  >{{ parseTime(scope.row[item.prop]) }}</span>
              <el-switch
                v-else-if="item.prop == 'status'"
                v-model="scope.row[item.prop]"
                :active-value="0"
                :inactive-value="1"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
              <span v-else-if="item.prop == 'auth'">
                {{getAuth(scope.row[item.prop])}}
              </span>
              <span v-else >{{ scope.row[item.prop] }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除</el-button>
             </template>

          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>

    </el-row>

    <!-- 批改题目对话框 -->
    <el-dialog title="批改题目" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="correctionForm" label-width="80px">
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="correctionForm.status"
            placeholder="选择状态"
            clearable
          >
            <el-option
              v-for="dict in enums.sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="难度" prop="difficultyId">
          <el-select
            v-model="correctionForm.difficultyId"
            filterable
            clearable
            remote
            reserve-keyword
            placeholder="输入难度名称"
            :remote-method="remoteGetDifficulty"
            :loading="problemDifficultyLoading">
            <el-option
              v-for="item in difficultyList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="auth">
          <el-select
            v-model="correctionForm.auth"
            placeholder="类型"
            clearable
          >
            <el-option
              v-for="dict in authList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="题库" prop="problemTypeId">
          <el-select
            v-model="correctionForm.problemTypeId"
            filterable
            remote
            reserve-keyword
            placeholder="输入题库名称"
            clearable
            :remote-method="remoteGetProblemType"
            :loading="problemTypeLoading">
            <el-option
              v-for="item in problemTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <span><i class="el-icon-warning"/> <span style="color: red">字段留空则不会对原有的数据进行改动</span></span>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import * as api from '@/api/problem'
import * as tagApi from '@/api/tag'
import * as problemTypeApi from '@/api/problemType'
import {list as getDifficultyList} from '@/api/difficulty'
import { addUser, listUser, updateUser } from '@/api/system/user'
import * as problemApi from '@/api/problem'
import { correctionProblem } from '@/api/problem'
import reference from  "@/components/Reference/reference"
export default {
  name: "problem",
  data() {
    return {
      sys_normal_disable:[
        {
          value:0,
          label:"正常"
        },
        {
          value:1,
          label:"禁用"
        }
      ],
      authList:[
        {
          value:0,
          label:"公开"
        },
        {
          value:1,
          label:"私有"
        },
        {
          value:2,
          label:"比赛"
        }
      ],
      options:[],
      userLoading:false,
      tagLoading:false,
      problemTypeLoading:false,
      problemDifficultyLoading:false,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      data: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      multiple:true,
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      //批改表单
      correctionForm:{},
      //选中列表
      selectData:[],
      userList:[],
      //题库id
      problemTypeId:"",
     // 查询参数
      queryParams: {
        pageNum: 1,
        tagIds:[],
        pageSize: 10,
        authorId:null,
        problemId:null,
        problemTypeId:null,
        title:undefined,
        status: undefined,
        auth:undefined,
        difficultyId:undefined
      },
      tagList:[],
      problemTypeList:[],
      difficultyList:[],
      // 列信息
      columns: [
        { label: `id`, visible: false, prop:"id"},
        { label: `编号`, visible: true, prop:"problemId"},
        { label: `标题`, visible: true, prop:"title" , width:"200px"},
        { label: `难度`, visible: true, prop:"difficultyName"},
        { label: `标签`, visible: true, prop:"tagNames"},
        { label: `类型`, visible: true, prop:"auth"},
        { label: `状态`, visible: true, prop:"status"},
        { label: `修改时间`, visible: false, prop:"updateTime" },
        { label: `创建时间`, visible: false, prop:"createTime" },
      ],
      // 表单校验
      rules: {
        name: [
          { required: true, message: "分类名称不能为空", trigger: "blur" },
          { min: 1, max: 7, message: '分类名称长度必须介于 1 和 7 之间', trigger: 'blur' }
        ]
      },
    };
  },
  mixins:[reference],
  async created() {
    await this.getList();
    if(this.type == 3){
      this.remoteGetTagList()
      this.remoteGetProblemType();
      this.remoteGetDifficulty();
    }
  },
  methods: {
    getAuth(auth){
      return this.authList.filter(item => item.value == auth)[0].label
    },
    /** 查询列表 */
    async getList() {
      this.loading = true;
      const res = await api.list(this.addDateRange(this.queryParams, this.dateRange));
      this.data = res.data.rows;
      //bug,单选且选中过。单选的话如果数据更新之后不会保留之前选中的数据，需要手动再次选中
      if(this.type == 1 && this.selectData.length > 0){
        this.$refs.mainTable.setCurrentRow(this.selectData[0]);
      }
      this.total = res.data.total;
      this.loading = false;
    },
    /** 状态修改 */
    handleStatusChange(row) {
      let text = row.status === 1 ? "停用" : "启用";
      this.$modal.confirm('确认要'+ text + '？').then(function() {
        return api.changeStatus(row.id, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === 0 ? 1 : 0;
      });
    },
    /**  表单重置 */
    reset() {
      this.form = {}
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let Ids = this.selectData.map(item => item.id);
      if(row && row.id)
        Ids = [row.id]
      this.$modal.confirm('是否确认删除').then(function() {
        return api.del(Ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 复制按钮操作 */
    copyProblem(row) {
      let Ids = this.selectData.map(item => item.id);
      if(row && row.id)
        Ids = [row.id]
      this.$modal.confirm('是否确认复制？').then(function() {
        return api.copyProblem(Ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("复制成功");
      }).catch(() => {});
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push({
        path:`/addProblem`,
        query:{
          id:row.id
        }
      });
    },
    /** 新增按钮操作 */
    handleAdd(){
      this.$router.push({
        path:`/addProblem`,
      });
    },
    //远程查询用户
    remoteGetUserList(query){
      this.userLoading = true;
      listUser({ nickName: query }).then(res => {
        this.userList = res.rows;
        this.userLoading = false;
      })
    },
    //远程查标签
    remoteGetTagList(query){
      this.tagLoading = true;
      tagApi.list({ name: query }).then(res => {
        this.tagList = res.data.rows;
        console.log(this.tagList)
        this.tagLoading = false;
      })
    },
    //远程查题库
    remoteGetProblemType(query){
      this.problemTypeLoading = true;
      problemTypeApi.list({ name: query }).then(res => {
        this.problemTypeList = res.data.rows;
        this.problemTypeLoading = false;
      })
    },
    //远程查难度
    remoteGetDifficulty(query){
      this.problemDifficultyLoading = true;
      getDifficultyList({ name: query }).then(res => {
        this.difficultyList = res.data.rows;
        this.problemDifficultyLoading = false;
      })
    },
    //上传校验
    beforeUpload(file){
      console.log(file.type)
      const isJPG = file.type === 'application/x-zip-compressed';
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传的内容只能是 ZIP 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传内容不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    //上传
    async defaultImport({ file }){
      console.log(file)
      // 创建一个 FormData 对象，用于构建请求参数
      const formData = new FormData();
      formData.append('file', file); // 将文件添加到 FormData 中

      problemApi.uploadProblemZip(formData).then(res=>{
        console.log(res)
      })

      //阻止默认上传行为
      return false;
    },
    //上传
    async fpsImport({ file }){
      console.log(file)
      // 创建一个 FormData 对象，用于构建请求参数
      const formData = new FormData();
      formData.append('file', file); // 将文件添加到 FormData 中

      problemApi.uploadFpsProblem(formData).then(res=>{
        console.log(res)
      })

      //阻止默认上传行为
      return false;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.correctionForm = {}
      // this.resetForm("correctionForm");
    },
    /** 批改提交按钮 */
    submitForm() {
      const param = []
      this.selectData.forEach(item => {
        param.push({id:item.id,...this.correctionForm})
      })
      api.correctionProblem(param).then(res => {
        this.$message.success("批改成功！")
        this.open = false;
      })
    },
    //批改
    handleCorrection(){
      this.correctionForm = {}
      this.open = true;
    },

  }
};
</script>
<style>

</style>
